package com.javandad.app.server.mail.entity;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.jdo.PersistenceManager;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;

import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.shared.entity.Mailable;
import com.javandad.app.shared.entity.Message;
import com.javandad.app.shared.entity.User;

public class MessageMail extends JMail {

	public MessageMail(Message msg) {
		super(Session.getDefaultInstance(new Properties(), null));
		adapt(msg);
	}

	protected void adapt(Mailable a) {
		Message msg = (Message) a;
		try {
			this.setSubject("A new message from " + msg.getSender()
					+ " < " + msg.getTitle() + " >.");
			String content = getContent(msg);
			this.setDataHandler(new DataHandler( new JMail.HTMLDataSource(content))) ;
			this.setFrom(new InternetAddress("javandad.info@gmail.com",
					"JaVandad"));
			PersistenceManager pm = PMFSingleton.getPM();
			DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();
			User receiver = dbm.getUser(msg.getReceiver(), pm);
			this.addRecipient(RecipientType.TO, new InternetAddress(receiver
					.getEmail()));
			pm.close();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

	}
	
	private String getContent(com.javandad.app.shared.entity.Message msg){
		String c = "";
		
		c = "<table><tr><td>" +
				"You have received the following message from " + msg.getSender() + " at " + msg.getDateOfDelivery() +
				"</td></tr>" +
				"<tr><td><b>" +
				  msg.getContent() +
				"</b></td></tr><tr><td>" +
				"link : <a href='"+ "" +"' >javandad.appspot.com</a>" +
				"</td></tr>" + 
				"</table>";
			
			

		
		
		return c;
	}
	

}
